import { apiUrl }                         from         '@/api/url';
import { lang }                           from         '@/workers/util/http';
import { compare,accAdd,countNum,formatDate,accMul }   from '@/workers/util/util';

let privateSocket = null;           // socket连接
let pingCount = 0;                  // ping次数
let pongCount = 0;                  // pong次数
let pingPongTimer = null;           // pingPong定时器
let connectTimer = null;            // 连接过程定时器
let type = '';                      // 当前合约类型
let Otoken = '';
let uid = '';
let onLine = true;                  // 当前是否连接网络

let pageStatus = true;              // 页面是否展示在前台
let router = '';                    // 当前页面路由

function calc(ev){
    // if(ev.data === 'zip_ready_for_1') return
    if(ev.data === 'pong'){
        pongCount++;
    } else { 
        if(ev && ev.data != 'input error' && ev.data && ev.data.includes('{')){
            let res = [];
            try{
                res = JSON.parse(ev.data);
            }catch(e){
                console.log('socket返回JSON数据格式错误')
            }
            if(Array.isArray(res)) return
            //更新余额(持仓)
            if(res.action === 'PushOrder' || res.action === 'PushTriggerOrder' || res.action === 'PushAccount' || res.action === 'PushPosition'){
                postMessage({
                    type:type,
                    action:'refreshBalance',
                    value:+new Date()
                })
            }
            //没有权限进入(暂定认为是token无效)
            if(res.action === 'RecvUserLogin' && res.errorMsg === 'UserNoPermission'){
                postMessage({
                    type:type,
                    action:'UserNoPermission',
                    value:{}
                })
            }
        }
    }
}

function checkPingPong(){
    // 检测pingPong是否异常(连接是否异常)
    if(pingCount - pongCount >= 3 && pageStatus){
        pingCount = 0;
        pongCount = 0;
        clearInterval(pingPongTimer);
        clearTimeout(connectTimer);
        if(privateSocket) privateSocket.close();
        privateSocket = null;
        setTimeout(()=>{
            privateConnect().then(res => {
                console.log('重连')
            })
        },1000)
    }
}

function sendPing(){
    // 发送ping
    if(!pageStatus) return
    privateConnect().then(function(){
        privateSocket.send('ping');
        pingCount++;
        // clearTimeout(pingPongTimer);
        // pingPongTimer = setTimeout(sendPing,4000);
        checkPingPong();
    })
}

function privateConnect(){
    // 连接socket操作
    if(!Otoken) return Promise.resolve()
    return new Promise(resolve => {
        // console.log(privateSocket)
        if(privateSocket && privateSocket.readyState === 1 || process.env.PRODUCT_TYPE === 'partner'){
            // socket连接正常
            resolve();
            return
        }
        if(privateSocket && privateSocket.readyState != 1){
            // 连接异常
            privateSocket.close();
            setTimeout(() => {
                connect();
            },1000)
        }
        if(!privateSocket) connect();
        function connect(){
            clearInterval(pingPongTimer);
            clearTimeout(connectTimer);
            privateSocket = new WebSocket(apiUrl.spotPrivateWs);
            privateSocket.onopen = function(){
                // console.log('连接成功')
                //连接成功
                pingCount = 0;
                pongCount = 0;
                clearInterval(pingPongTimer);
                clearTimeout(connectTimer);
                initSend();
                pingPongTimer = setInterval(()=>{
                    sendPing();
                },5000)
                resolve();
            }
            privateSocket.onmessage = calc;
            privateSocket.onerror = function(err){

            }
            // 延迟检测是否连接成功
            connectTimer = setTimeout(()=>{
                privateSocket.close();
                setTimeout(() => {
                    connect();
                },1000)
            },10*1000)
        }
    })
}

function initSend(){
    //发送订阅信息
    // privateSocket.send('zip=1');
    privateSocket.send(JSON.stringify({
        SendUserLogin:{
            Token:Otoken
        }
    }))
    privateSocket.send(JSON.stringify({
        SendTopicAction:{
            Action: "1", // 订阅操作 '0':Clear/全部退订; '1':Sub/订阅 '2':UnSub/退订
            FilterValue: uid,
            LocalNo: 12, // 大于0，自定义,一次会话中不能重复
            ResumeNo: 0, // 续传号:0是从头开始,-1是从服务端最新位置续传
            TopicID: "3"
        }
    }))
}

// 关闭websocket连接
function closeWs(){
    setTimeout(()=>{
        pingCount = 0;
        pongCount = 0;
        clearInterval(pingPongTimer);
        clearTimeout(connectTimer);
        if(privateSocket) privateSocket.close();
        privateSocket = null;
    },600)
}

//监听主线传来的信息(只处理 {type:'SpotLogin'}类型)
self.addEventListener('message', function (e) {
    let res = e.data;
    if(typeof res === 'object' && !Array.isArray(res) && (res.type === 'SpotLogin' || res.type === 'SwapSpot')){
        type = res.type;
        if(res.action === 'sendOtokenUid'){
            Otoken = res.value.Otoken;
            uid = res.value.uid;
            if(Otoken) {
                privateConnect().then(function(){
                
                })
            }else{
                if(privateSocket && privateSocket.readyState === 1){
                    privateSocket.close();
                }
            }
        }

        if(res.action === 'pageRouter'){
            router = res.value;
            if(router === '/Spot' || router === '/spot') {
                if(!privateSocket || privateSocket.readyState != 1){
                    console.log('initSwapConnect')
                    privateConnect().then(res => {
                        
                    })
                }
            }else{
                closeWs();
            }
        }
        
        if(res.action === 'pageStatus'){
            // 页面是否显示在前台
            let currentPageStatus = res.value === 'show'?true:false;
            if(pageStatus && !currentPageStatus){
                // 从前台返回到后台
                closeWs();
            }
            if(!pageStatus && currentPageStatus){
                // 从后台返回前台
                if(router === '/Spot' || router === '/spot'){
                    privateConnect().then(res => {
                        
                    })
                }
            }
            pageStatus = currentPageStatus;
        }
    }
}, false);